﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using AngleExpress.service;
using AngleExpress.utils;
using System.ComponentModel;

namespace AngleExpress
{
    class Service
    {
        private readonly HttpClient client;
        private readonly string baseUrl;
        private static Service instance;

        public static Service Instance()
        {
            if (instance == null)
            {
                instance = new Service();
            }
            return instance;
        }

        private Service()
        {
            baseUrl = System.Configuration.ConfigurationManager.AppSettings["ServiceUrl"];
            if (string.IsNullOrEmpty(baseUrl))
            {
                //Utils.ShowError("读取配置文件信息失败!请检查配置文件是否正确");
                //System.Windows.Application.Current.Shutdown();
                baseUrl = Global.ServiceUrl;
            }
            client = new HttpClient();
        }

        public async Task<LoginResult> Login(string username, string password)
        {
            List<KeyValuePair<string, string>> postParams = new List<KeyValuePair<string, string>>();
            postParams.Add(new KeyValuePair<string, string>("loginName", username));
            postParams.Add(new KeyValuePair<string, string>("password", password));
            LoginResult backRes = await Post<LoginResult>("/api/login",postParams);

            if (string.IsNullOrEmpty(backRes.errMsg))
            {
                if (backRes.code != 200)
                    backRes.errMsg = backRes.msg;
            }
            return backRes;
        }

        public async Task<SystemInfoResult> GetSystemConfig(string token)
        {
            string uri = "/api/angel/customer/customerList?principalId=" + token;
            SystemInfoResult backRes = await Get<SystemInfoResult>(uri);

            if (string.IsNullOrEmpty(backRes.errMsg))
            {
                if (backRes.code != 200)
                    backRes.errMsg = "api返回数据异常";
            }
            return backRes;
        }

        public async Task<PostUseRecordResult> PostUseRecord(string userID,string softwareId,int softerwareType,string ip)
        {
            List<KeyValuePair<string, string>> postParams = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("sysId", softwareId),
                new KeyValuePair<string, string>("principalId", userID),
                new KeyValuePair<string, string>("type", softerwareType.ToString()),
                new KeyValuePair<string,string>("ipStr",ip)
            };

            PostUseRecordResult backResult = await Post<PostUseRecordResult>("/api/angel/customer/insertRecord", postParams);
            if (string.IsNullOrEmpty(backResult.errMsg))
            {
                if (backResult.code != 200)
                    backResult.errMsg = "api返回数据异常";
            }
            return backResult;
        }

        public async Task<NotifyMsgResult> GetNotifyMsg(string userID)
        {
            string url = "/api/angel/customer/notifyMsg?principalId=" + userID;
            NotifyMsgResult result =await Get<NotifyMsgResult>(url);
            if (string.IsNullOrEmpty(result.errMsg))
            {
                if (result.code != 200)
                    result.errMsg = "api返回数据异常";
            }
            return result;
        }

        public async Task<UpdateNotifyStatusResult> UpdateNotifyRead(string notifyID)
        {
            string url = "/api/angel/customer/updateStatus?id=" + notifyID;
            UpdateNotifyStatusResult result = await Get<UpdateNotifyStatusResult>(url);
            if (string.IsNullOrEmpty(result.errMsg))
            {
                if (result.code != 200)
                    result.errMsg = "api返回数据异常";
            }
            return result;
        } 

        private async Task<T> Post<T>(string reletiveUrl, List<KeyValuePair<string, string>> postParams) where T : MyHttpResult, new()
        {
            string uri = baseUrl + reletiveUrl;
            FormUrlEncodedContent content = new FormUrlEncodedContent(postParams);
            HttpResponseMessage response;
            T backResult;

            try
            {
                response = await client.PostAsync(uri, content);
            }
            catch (HttpRequestException e)
            {
                return makeErrResult<T>("网络请求异常：" + e.InnerException.Message);
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return makeErrResult<T>("网络请求异常,状态码：" + (int)response.StatusCode);
            }

            string result = await response.Content.ReadAsStringAsync();
            try
            {
                backResult = JsonConvert.DeserializeObject<T>(result);
            }
            catch (Exception)
            {
                return makeErrResult<T>("json反序列化失败");
            }

            return backResult;
        }

        private async Task<T> Get<T>(string reletiveUrl) where T : MyHttpResult, new()
        {
            string uri = baseUrl + reletiveUrl;
            HttpResponseMessage response;
            T backResult;

            try
            {
                response = await client.GetAsync(uri);
            }
            catch (HttpRequestException e)
            {
                return makeErrResult<T>("网络请求异常：" + e.InnerException.Message);
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return makeErrResult<T>("网络请求异常,状态码：" + (int)response.StatusCode);
            }

            string result = await response.Content.ReadAsStringAsync();
            try
            {
                backResult = JsonConvert.DeserializeObject<T>(result);
            }
            catch (Exception)
            {
                return makeErrResult<T>("json反序列化失败");
            }

            return backResult;
        }

        T makeErrResult<T>(string errmsg) where T : MyHttpResult, new()
        {
            return new T() { errMsg = errmsg };
        }
    }
}


